import BaseChart from '@/components/data/baseChart.js';
import ChartTypeList from '@/components/data/chartType.js';
import API from '@/components/data/api.js';
import DataSourceUtil from '@/components/util/dataSourceUtil.js';
import echarts from 'echarts';
import 'echarts-wordcloud';
/**
 *
 * @param {图表类型} type
 * @param {选择变量} dataOp
 * @param {数据} dataList
 * @param {图表选项} baseOption
 * @param {地图名称} mapName
 */
function createChartData(type, dataOp, dataList, baseOption, mapName) {
  if (type == 'line' || type == 'bar') {
    //折线和柱形
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.line));
    var x = [],
      y = [],
      xCode = dataOp.category.code,
      yCode = [];
    for (var j = 0; j < dataOp.value.length; j++) {
      y.push([]);
      yCode.push(dataOp.value[j].code);
    }
    if (!xCode || yCode.length == 0) {
      return null;
    }

    for (var i = 0; i < dataList.length; i++) {
      x.push(dataList[i][xCode]);
      for (var j = 0; j < dataOp.value.length; j++) {
        y[j].push(dataList[i][yCode[j]]);
      }
    }
    baseOption.xAxis[0].data = x;

    for (var j = 0; j < dataOp.value.length; j++) {
      if (baseOption.series[j]) {
        baseOption.series[j].type = type;
        baseOption.series[j].data = y[j];
        baseOption.series[j].name = baseOption.series[j].name
          ? baseOption.series[j].name
          : dataOp.value[j].name;
      } else {
        baseOption.series[j] = { type: type, data: y[j], name: dataOp.value[j].name };
      }
    }
    return baseOption;
  } else if (type == 'pie' || type == 'funnel' || type == 'word-cloud' || type == 'gauge') {
    //饼图 漏斗图 字符云 仪表盘
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.pie));

    var data = [],
      xCode = dataOp.name.code,
      yCode = dataOp.value.code;
    if (!xCode || !yCode) {
      return null;
    }

    for (var i = 0; i < dataList.length; i++) {
      data.push({ name: dataList[i][xCode], value: dataList[i][yCode] });
    }

    if (baseOption.series[0]) {
      baseOption.series[0].name = baseOption.series[0].name
        ? baseOption.series[0].name
        : dataOp.value.name;
      baseOption.series[0].type = type == 'word-cloud' ? 'wordCloud' : type;
      baseOption.series[0].data = data;
    } else {
      baseOption.series[0] = {
        name: dataOp.value.name,
        type: type == 'word-cloud' ? 'wordCloud' : type,
        data: data,
      };
    }
    return baseOption;
  } else if (type == 'scatter') {
    //散点
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.scatter));

    var data = [],
      xCode = dataOp.x.code,
      yCode = dataOp.y.code;
    if (!xCode || !yCode) {
      return null;
    }

    for (var i = 0; i < dataList.length; i++) {
      data.push([dataList[i][xCode], dataList[i][yCode]]);
    }
    if (baseOption.series[0]) {
      baseOption.series[0].data = data;
      baseOption.series[0].type = type;
    } else {
      baseOption.series[0] = {
        type: type,
        data: data,
      };
    }

    return baseOption;
  } else if (type == 'radar') {
    //雷达图
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.radar));
    var indicator = [],
      name = dataOp.name.code,
      max = dataOp.max.code,
      value = [];

    for (var j = 0; j < dataOp.value.length; j++) {
      value.push([]);
    }
    if (!name || !max || value.length == 0) {
      return null;
    }

    for (var i = 0; i < dataList.length; i++) {
      indicator.push({ name: dataList[i][name], max: dataList[i][max] });
      for (var j = 0; j < dataOp.value.length; j++) {
        value[j].push(dataList[i][dataOp.value[j].code]);
      }
    }
    baseOption.radar[0].indicator = indicator;
    var data = [];
    for (var j = 0; j < dataOp.value.length; j++) {
      data.push({
        name: dataOp.value[j].name,
        value: value[j],
      });
    }
    if (baseOption.series[0]) {
      baseOption.series[0].type = type;
      baseOption.series[0].data = data;
    } else {
      baseOption.series[0] = {
        type: type,
        data: data,
      };
    }

    return baseOption;
  } else if (type == 'tree') {
    //树
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.tree));

    var name = dataOp.name.code,
      node = dataOp.node.code,
      value = dataOp.value.code;

    if (!name || !node || !value) {
      return null;
    }

    var d = [];
    dataList.forEach(function(item) {
      d.push({ name: item[name], node: item[node], value: item[value] });
    });
    function toTree(data) {
      // 删除 所有 children,以防止多次调用
      data.forEach(function(item) {
        delete item.children;
      });

      // 将数据存储为 以 name 为 KEY 的 map 索引数据列
      var map = {};
      data.forEach(function(item) {
        map[item.name] = item;
      });

      var val = [];
      data.forEach(function(item) {
        // 以当前遍历项，的node,去map对象中找到索引的id
        var parent = map[item.node];
        // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中

        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
          val.push(item);
        }
      });
      data.forEach(function(item) {
        if (item.children && item.children.length > 0) {
          delete map[item.name].value;
        }
        delete map[item.name].node;
      });
      return val;
    }
    if (baseOption.series[0]) {
      baseOption.series[0].type = type;
      baseOption.series[0].data = toTree(d);
    } else {
      baseOption.series[0].data = { type: type, data: toTree(d) };
    }

    return baseOption;
  } else if (type == 'map') {
    //地图
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.map));
    var name = dataOp.name.code,
      value = dataOp.value.code,
      map = [],
      min = Number.POSITIVE_INFINITY,
      max = Number.NEGATIVE_INFINITY;

    if (!name || !value) {
      return null;
    }

    dataList.forEach(function(item) {
      map.push({ name: item[name], value: item[value] });
      min = min > item[value] ? item[value] : min;
      max = max < item[value] ? item[value] : max;
    });

    if (baseOption.visualMap) {
      baseOption.visualMap[0].min = min;
      baseOption.visualMap[0].max = max;
    } else {
      baseOption.visualMap[0] = {
        min: min,
        max: max,
      };
    }
    if (baseOption.series[0]) {
      baseOption.series[0].map = mapName;
      baseOption.series[0].data = map;
    } else {
      baseOption.series[0] = {
        map: mapName,
        data: data,
        type: type,
      };
    }

    return baseOption;
  } else if (type == 'graph') {
    //关系图
    baseOption = baseOption ? baseOption : JSON.parse(JSON.stringify(BaseChart.relate));
    var name = dataOp.name.code,
      source = dataOp.source.code,
      target = dataOp.target.code,
      x = dataOp.x.code,
      y = dataOp.y.code,
      value = dataOp.value.code,
      edge = dataOp.edge.code;
    if (!name || !source || !target || !x || !y || !value || !edge) {
      return null;
    }

    var data = [],
      link = [];
    dataList.forEach(function(item) {
      if (item[name]) {
        data.push({ name: item[name], x: item[x], y: item[y], value: item[value] });
      }
      link.push({ source: item[source], target: item[target], value: item[edge] });
    });
    if (baseOption.series[0]) {
      baseOption.series[0].type = type;
      baseOption.series[0].data = data;
      baseOption.series[0].links = link;
    } else {
      baseOption.series[0] = {
        type: type,
        data: data,
        links: link,
      };
    }

    return baseOption;
  }
  return null;
}
/**
 * 获取图表数据
 * @param {图表id} id 
 * @param {返回函数} callback 
 */
function getChart(id, callback) {
  $.post(API.getChart, { chartId: id }, function(res) {
    if (res.errCode == 0&&res.data.length==1) {
      var option = res.data[0];
      option.title =option.title? decodeURI(option.title):'--';
      option.chart_option = JSON.parse(option.chart_option);
      option.data_op = JSON.parse(option.data_op);
      callback(option);
    } else {
      callback(null);
    }
  });
}

/**
     * 获取图表选项
     * @param {图表设置} option
     * @param {数据} dataList
     */
  function  getChartData(option, dataList) {
      if (ChartTypeList[option.chart_type].name == 'map') {
        option.chart_option = createChartData(
          ChartTypeList[option.chart_type].name,
          option.data_op,
          dataList,
          option.chart_option,
          option.data_op.map
        );
      } else {
        option.chart_option =createChartData(
          ChartTypeList[option.chart_type].name,
          option.data_op,
          dataList,
          option.chart_option
        );
      }
      return option;
    }
/**
 * 获取图表数据和数据包
 * @param {图表id} id 
 * @param {返回函数} callback 
 */
function getChartAndData(id,callback){
  getChart(id,function(option){
    if(option){
      DataSourceUtil.loadDataSource(option.data_id,function(res){
        if(res&&res.dataList){
          option= getChartData(option,res.dataList);
          callback(option);
        }else{
          callback(null)
        }
      })
    }else{
      callback(null)
    }
    
  })
}
/**
 * 获取图表主题
 * @param {*} theme 
 * @param {*} callback 
 */
function getChartTheme(theme, callback) {
  $.get(API.themePath + theme + '.json', function(res) {
    echarts.registerTheme(theme, res);
    callback();
  });
}
/**
 * 生成图表
 * @param {元素id} id
 * @param {图表选项} option
 * @param {图表主题} theme
 * @param {返回函数} callback
 */
function createChart(id, option, theme, callback) {
  var elmt = document.getElementById(id);
  if (theme) {
    getChartTheme(theme, function() {
      var chart = echarts.init(elmt, theme,{renderer:'svg'});
      chart.setOption(option);
      callback(chart);
    });
  } else {
    var chart = echarts.init(elmt,'',{renderer:'svg'});
    chart.setOption(option);
    callback(chart);
  }
}
/**
 * 生成地图
 * @param {元素id} id
 * @param {图表选项} option
 * @param {地图名称} map
 * @param {图表主题} theme
 * @param {返回函数} callback
 */
function createMap(id, option, theme, map, callback) {
  var elmt = document.getElementById(id);
  
  if(theme){
    getChartTheme(theme,function(){
      $.get(API.mapPath + map + '.json', function(geoJson) {
        echarts.registerMap(map, geoJson);
        var chart = echarts.init(elmt, theme,{renderer:'svg'});
        chart.setOption(option);
        callback(chart);
      });      
    });
  }else{
    $.get(API.mapPath + map + '.json', function(geoJson) {
      echarts.registerMap(map, geoJson);
      var chart = echarts.init(elmt, '',{renderer:'svg'});
      chart.setOption(option);
      callback(chart);
    });  
  }

  
}

 /**
     * 设置图表option
     * @param {元素id} id
     * @param {图表设置} option
     * @param {返回函数} callback
     */
 function   setChart(id,option,callback) {
      if (ChartTypeList[option.chart_type].name == 'map') {
        createMap(id,
          option.chart_option,
          option.chart_theme,
          option.data_op.map,
          callback
        );
      } else {
        createChart(id, option.chart_option, option.chart_theme,callback);
      }
    }

    function getTemplate(id,callback){
      
      $.post(API.getTemplate, { tempId: id }, function(res) {
        if (res.errCode == 0) {
          var option = res.data[0];
          option.title = decodeURI(option.title);
          option.bg = JSON.parse(option.bg);
          for(var i=0;i<option.chartList.length;i++){
            option.chartList[i].pos=JSON.parse(option.chartList[i].pos);
            option.chartList[i].style=JSON.parse(option.chartList[i].style);
          }
          
         callback(option);
        } else {
          callback(null);
        }
      });
    }

export default {
  createChartData,
  getChartAndData,
  getChart,
  getChartData,
  getChartTheme,
  createChart,
  createMap,
  setChart,
  getTemplate

};
